package com.gfxy.modules.classtime.controller;

import java.io.File;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gfxy.modules.classtime.service.impl.ClasstimeUploadServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.oConvertUtils;
import com.gfxy.modules.classtime.entity.GfxyTClasstimeUpload;
import com.gfxy.modules.classtime.service.IGfxyTClasstimeUploadService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 课时文件上传
 * @Author: jeecg-boot
 * @Date:   2021-05-25
 * @Version: V1.0
 */
@Api(tags="课时文件上传")
@RestController
@RequestMapping("/classtime/classtimeUpload")
@Slf4j
public class GfxyTClasstimeUploadController extends JeecgController<GfxyTClasstimeUpload, IGfxyTClasstimeUploadService> {
	@Autowired
	private IGfxyTClasstimeUploadService gfxyTClasstimeUploadService;

	 @Autowired
	 private ClasstimeUploadServiceImpl classtimeUploadService;
	 @Value(value="${jeecg.uploadType}")
	 private String uploadType;

	 @Value(value = "${jeecg.path.upload}")
	 private String uploadpath;

	 /**
	 * 分页列表查询
	 *
	 * @param gfxyTClasstimeUpload
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "课时文件上传-分页列表查询")
	@ApiOperation(value="课时文件上传-分页列表查询", notes="课时文件上传-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(GfxyTClasstimeUpload gfxyTClasstimeUpload,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<GfxyTClasstimeUpload> queryWrapper = QueryGenerator.initQueryWrapper(gfxyTClasstimeUpload, req.getParameterMap());
		Page<GfxyTClasstimeUpload> page = new Page<GfxyTClasstimeUpload>(pageNo, pageSize);
		IPage<GfxyTClasstimeUpload> pageList = gfxyTClasstimeUploadService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	 /**
	  * 分页列表查询
	  *
	  * @param gfxyTClasstimeUpload
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "gfxy_t_classtime_upload-分页列表查询,没有则插入")
	 @ApiOperation(value="gfxy_t_classtime_upload-分页列表查询,没有则插入", notes="gfxy_t_classtime_upload-分页列表查询,没有则插入")
	 @GetMapping(value = "/listAndInsert")
	 public Result<?> queryPageListAndInsert(GfxyTClasstimeUpload gfxyTClasstimeUpload,
											 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
											 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
											 HttpServletRequest req){


		 QueryWrapper<GfxyTClasstimeUpload> queryWrapper = QueryGenerator.initQueryWrapper(gfxyTClasstimeUpload, req.getParameterMap());
		 Page<GfxyTClasstimeUpload> page = new Page<GfxyTClasstimeUpload>(pageNo, pageSize);
		 IPage<GfxyTClasstimeUpload> pageList = gfxyTClasstimeUploadService.page(page, queryWrapper);
		 if(pageList.getRecords()==null || pageList.getRecords().isEmpty()){

			 String year = gfxyTClasstimeUpload.getYear();
			 List<GfxyTClasstimeUpload> saveList = new ArrayList<>(12);
			 for (int i = 1; i <=12 ; i++) {
				 GfxyTClasstimeUpload upload = new GfxyTClasstimeUpload();
				 upload.setYear(year);
				 upload.setMonth(i);
				 upload.setLoadStatus(0);
				 upload.setUploadStatus(0);
				 upload.setFilePath("");
				 saveList.add(upload);
			 }
			 gfxyTClasstimeUploadService.saveBatch(saveList);

			 pageList = gfxyTClasstimeUploadService.page(page, queryWrapper);
		 }
		 return Result.OK(pageList);
	 }
	
	/**
	 *   添加
	 *
	 * @param gfxyTClasstimeUpload
	 * @return
	 */
	@AutoLog(value = "课时文件上传-添加")
	@ApiOperation(value="课时文件上传-添加", notes="课时文件上传-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody GfxyTClasstimeUpload gfxyTClasstimeUpload) {
		gfxyTClasstimeUploadService.save(gfxyTClasstimeUpload);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param gfxyTClasstimeUpload
	 * @return
	 */
	@AutoLog(value = "课时文件上传-编辑")
	@ApiOperation(value="课时文件上传-编辑", notes="课时文件上传-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody GfxyTClasstimeUpload gfxyTClasstimeUpload) {

		gfxyTClasstimeUploadService.updateById(gfxyTClasstimeUpload);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "课时文件上传-通过id删除")
	@ApiOperation(value="课时文件上传-通过id删除", notes="课时文件上传-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		gfxyTClasstimeUploadService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "课时文件上传-批量删除")
	@ApiOperation(value="课时文件上传-批量删除", notes="课时文件上传-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.gfxyTClasstimeUploadService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "课时文件上传-通过id查询")
	@ApiOperation(value="课时文件上传-通过id查询", notes="课时文件上传-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		GfxyTClasstimeUpload gfxyTClasstimeUpload = gfxyTClasstimeUploadService.getById(id);
		if(gfxyTClasstimeUpload==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(gfxyTClasstimeUpload);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param gfxyTClasstimeUpload
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GfxyTClasstimeUpload gfxyTClasstimeUpload) {
        return super.exportXls(request, gfxyTClasstimeUpload, GfxyTClasstimeUpload.class, "课时文件上传");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GfxyTClasstimeUpload.class);
    }

	 /**
	  * 文件上传统一方法
	  * @param request
	  * @param response
	  * @return
	  */
	 @PostMapping(value = "/upload")
	 public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
		 Result<?> result = new Result<>();
		 String savePath = "";
		 String bizPath = request.getParameter("biz");
		 String year = request.getParameter("year");
		 String month = request.getParameter("month");
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
		 System.out.println("upload");
		 if(oConvertUtils.isEmpty(bizPath)){
			 if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){

				 bizPath = "upload";
			 }else{
				 bizPath = "";
			 }
		 }

		 savePath = this.uploadLocal(file,bizPath);

		 if(oConvertUtils.isNotEmpty(savePath)){

		 	gfxyTClasstimeUploadService.importData(year,month,savePath);
//			classtimeUploadService.importData(year,savePath);

		 	result.setMessage(savePath);
		 	result.setSuccess(true);
		 }else {
			 result.setMessage("上传失败！");
			 result.setSuccess(false);
		 }
		 return result;
	 }



	 /**
	  * 本地文件上传
	  * @param mf 文件
	  * @param bizPath  自定义路径
	  * @return
	  */
	 private String uploadLocal(MultipartFile mf,String bizPath){
		 try {
			 String ctxPath = uploadpath;
			 String fileName = null;
			 File file = new File(ctxPath + File.separator + bizPath + File.separator );
			 if (!file.exists()) {
				 file.mkdirs();// 创建文件根目录
			 }
			 String orgName = mf.getOriginalFilename();// 获取文件名
			 orgName = CommonUtils.getFileName(orgName);
			 if(orgName.indexOf(".")!=-1){
				 fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
			 }else{
				 fileName = orgName+ "_" + System.currentTimeMillis();
			 }
			 String savePath = file.getPath() + File.separator + fileName;

			 File savefile = new File(savePath);
			 FileCopyUtils.copy(mf.getBytes(), savefile);
			 String dbpath = null;
			 if(oConvertUtils.isNotEmpty(bizPath)){
				 dbpath = bizPath + File.separator + fileName;
			 }else{
				 dbpath = fileName;
			 }
			 if (dbpath.contains("\\")) {
				 dbpath = dbpath.replace("\\", "/");
			 }
			 return dbpath;
		 } catch (IOException e) {
			 log.error(e.getMessage(), e);
		 }
		 return "";
	 }

 }
